﻿using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;

namespace KBWebApi.Common
{
    public class SqlDBHelper
    {
        //获取DBSetting下的ConnectString值

        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令，通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        /// 此类为抽象类，
        /// 不允许实例化，在应用时直接调用即可
        /// </summary>
        //  abstract   抽象类标识
        public abstract class SqlHelper
        {
            //加载appsetting.json
            static IConfiguration configuration = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json").Build();

            private static SqlSugarScope db;

            /// <summary>
            /// 数据库连接字符串
            /// </summary>
            private static readonly string connectionString = configuration["Connection:dbContent"];   //获取DBSetting下的ConnectString值
            private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

            public static SqlSugarScope GetDB()
            {
                db = new SqlSugarScope(new ConnectionConfig()
                 {
                     ConnectionString = configuration["Connection:dbContent"],
                     DbType = SqlSugar.DbType.SqlServer,//设置数据库类型        
                     IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放       
                     InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息    
                 });

                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                    // LogHelper.LogWrite(sql + "\r\n" +Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                };
                return db;
            }
        }
    }
}
